﻿using System;
using System.Windows.Forms;

namespace Microsoft.Office.PowerPoint.STAMP.Controls
{
    /// <summary>
    /// A text box used to display percentages.
    /// </summary>
    public partial class PercentageTextBox : ToolStripTextBox
    {
        /// <summary>
        /// Initializes a new instance of the <see cref="MillisecondTextBox"/> class.
        /// </summary>
        public PercentageTextBox()
        {
            InitializeComponent();
        }

        private void MillisecondTextBox_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar == '\b')
                return;
            string tempText = LoadText(e.KeyChar.ToString());
            int result;
            if (tempText != string.Empty && !int.TryParse(tempText, out result))
                e.Handled = true;
        }

        private string LoadText(string newText)
        {
            string tempText = Text.Remove(SelectionStart, SelectionLength);
            tempText = tempText.Insert(SelectionStart, newText);
            tempText = TrimText(tempText);
            return tempText;
        }

        private static string TrimText(string text)
        {
            string testText = text;
            testText = testText.TrimEnd('%',' ').TrimStart(' ');
            return testText;
        }

        private void MillisecondTextBox_Enter(object sender, EventArgs e)
        {
            Text = TrimText(Text);
            SelectAll();
        }

        private void MillisecondTextBox_Leave(object sender, EventArgs e)
        {
            int result = Value;
            UpdateText(result);
        }

        private void UpdateText(float value)
        {
            Text = value.ToString("0 '%'");
        }

        /// <summary>
        /// Gets the value.
        /// </summary>
        public int Value
        {
            get
            {
                string tempText = TrimText(Text);
                int result;
                int.TryParse(tempText, out result);
                return result;
            }
            set { UpdateText(value); }
        }
    }
}
